<?php
require_once dirname(__FILE__) . '/../../../incls/php/dbutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/miscutils.class.php';
require_once dirname(__FILE__) . '/../../../incls/php/config.php';
$myPdo = DbUtils::createPdoInst();
$page_id = MiscUtils::getParam('i', 0);


$find = MiscUtils::getParam('find', '');
$cat = MiscUtils::getParam('cat', 0);

$cond_vals = new stdClass(); 
$cond_vals->c = '';
$cond_vals->v = array();
$cond_vals->c = "t.name LIKE :v1";
$cond_vals->v[":v1"] = "%$find%";

if ($cat == 1) {
  $cond_vals->c .= " AND t.status = :v2";
  $cond_vals->v[":v2"] = 1;
} else if ($cat == 2) {
  $cond_vals->c .= " AND t.status = :v2";
  $cond_vals->v[":v2"] = 0;
} else if ($cat == 3) {
  $cond_vals->c .= " AND t.alert__ = :v2";
  $cond_vals->v[":v2"] = 1;
}

//MiscUtils::dump($cond_vals);
$SIZE = 50;
$page = MiscUtils::getParam('p', 1);
$order = MiscUtils::getParam('o', 't.name');
$queue = MiscUtils::getParam('q', 'ASC');
$opt = new stdClass();
$opt->select_expr = 'id, track_id, date, enabled_stock, enabled_delivery, enabled_member_price, brand_id, category_id, name, price, stock, stock_alert, intro, status, sold__, alert__';
$items = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product', $cond_vals, $order, $queue, $page, $SIZE, $opt);
foreach ($items->d as $item) {
  $cond_vals = new stdClass(); 
  $cond_vals->c = 't.product_track_id = :v1';
  $cond_vals->v = array(':v1' => $item->track_id);
  $opt = new stdClass();
  $opt->select_expr = 'SUM(t.id) AS sum';
  $total_attrs = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_attr', $cond_vals,  NULL, NULL, NULL, NULL, $opt)->d[0]->sum;
  if ($total_attrs > 0) {
    $cond_vals = new stdClass(); 
    $cond_vals->c = 't.product_track_id = :v1';
    $cond_vals->v = array(':v1' => $item->track_id);
    $opt = new stdClass();
    $opt->select_expr = 't.stock, t.stock_alert';
    $objects = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_product_object', $cond_vals,  NULL, NULL, NULL, NULL, $opt)->d;
    
    $item->_stock = 0;
    foreach ($objects as $obj) {
      $item->_stock += $obj->stock;
    }
  } else {
    $item->_stock = $item->stock;
  }
}
$brands = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_brand', NULL, 't.name', 'ASC', NULL, NULL, NULL)->d;
$categories = DbUtils::get($myPdo,  TABLE_NAME_PREFIX_PLUGIN . 'ecom_category', NULL, 't.name', 'ASC', NULL, NULL, NULL)->d;

function get_brand($id) {
  global $brands;
  foreach ($brands as &$obj) {
    if ($obj->id == $id) {
      return $obj->name;
    }
  }
  return '-';
}

function get_category($id) {
  global $categories;
  foreach ($categories as &$obj) {
    if ($obj->id == $id) {
      return $obj->name;
    }
  }
  return '-';
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<style>
* {
  font-family: Trebuchet MS;
  font-size: 12px;
  padding: 0;
  margin: 0;
}
table.list {
  border-left: 1px solid #666;
  border-top: 1px solid #666;
  font-size: 12px;
  width: 950px;
}
table.list th.sort {
  text-align: left;
  height: 28px;
  background-color: #222;
  padding: 0 5px; 
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  font-weight: bold;
  vertical-align: middle;
  cursor: pointer;
  color: #fff;
}
table.list tr.rowodd td {
  padding: 0 5px;
  height: 25px;
  background-color: #eee;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.roweven td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
  vertical-align: middle;
}
table.list tr.rowodd:hover td {
  background-color: #f4f3b2;
}
table.list tr.roweven:hover td {
  background-color: #f4f3b2;
}
table.list tr.none td {
  padding: 0 5px;
  height: 25px;
  background-color: #fff;
  border-right: 1px solid #666;
  border-bottom: 1px solid #666;
  word-wrap: break-word;
}
.imgbtn {
  background-image: url(assets/imgs/add.png);
  background-repeat: no-repeat;
  background-position: 5px 2px;
  padding: 5px 5px 5px 30px;
  border: 1px solid #666;
  background-color: #fff;
  cursor: pointer;
  border-radius: 3px;
}
.imgbtn:hover {
  background-color: #eee;
}
.imgico {
  cursor: pointer;
}
table.form {
  background-color: #fff;
  border-top: 1px solid #222;
  border-left: 1px solid #222;
}
table.form th.header {
  text-align: left;
  color: #fff;
  background-color: #222;
  padding-left: 5px;
  font-weight: bold;
  height: 25px;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}

table.form td {
  padding: 3px 5px; 
  vertical-align: middle;
}
table.form td.title {
  background-color: #666;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
  width: 150px;
  color: #fff;
}
table.form td.content {
  width: 300px;
  padding: 0;
  border-bottom: 1px solid #222;
  border-right: 1px solid #222;
}
table.form td.content input {
  width: 98%;
  height: 20px;
  border: 0;
  padding-left: 2px;
}
.searchwrapper {
  width:310px; /*follow your image's size*/
  height:40px;/*follow your image's size*/
  background-image:url(assets/imgs/searchbox.jpg);
  background-repeat:no-repeat; /*important*/
  padding:0px;
  margin:0px;
  position:relative; /*important*/
}
.searchbox {
  border:0px; /*important*/
  background-color:transparent; /*important*/
  position:absolute; /*important*/
  top:4px;
  left:9px;
  width:256px;
  height:31px;
  color:#fff;
  outline: none;
}
.searchbox_submit {
  border:0px; /*important*/
  background-color:transparent; /*important*/
  position:absolute; /*important*/
  top:4px;
  left:265px;
  width:32px;
  height:32px;
}
.styled-select {
  width: 240px;
  height: 34px;
  overflow: hidden;
  background: url(assets/imgs/down_arrow_select.jpg) no-repeat right #ddd;
  border: 1px solid #ccc;
  margin-left: 5px;
}
.styled-select select {
  background: transparent;
  width: 268px;
  padding: 5px;
  font-size: 16px;
  line-height: 1;
  border: 0;
  border-radius: 0;
  height: 34px;
  -webkit-appearance: none;
}
.styled-select option {
  padding: 5px;
  font-size: 16px;
  line-height: 1;
}
</style>
</head>
<body>
<div>
  <table cellPadding=0 cellSpacing=0>
    <tr>
      <td>
        <div class="searchwrapper">
          <input type="text" class="searchbox" id="s_kw" value="<?php echo $find; ?>" onkeypress="enter(event);"/>
          <input type="image" src="assets/imgs/blank.png" class="searchbox_submit" value="" onclick="find();"/>
        </div>
      </td>
      <td>
        <div class="styled-select">
          <select id="s_cat" onchange="find();">
            <option>All Products</option>
            <option>Available Only</option>
            <option>Unavailable Only</option>
            <option>Out of Stock Only</option>
          </select>
        </div>
      </td>
    </tr>
  </table>
</div>
<div>&nbsp;</div>
<button class="imgbtn" onclick="parent.location.href=parent.document.URL.replace('#', '') + '&script=index_product';">New Product</button>
<div>
  <table class="list" style="margin-top: 5px;" cellPadding="0" cellSpacing="0">
    <tr>
      <th class="sort" onclick="set_order('name')">Product Name</th>
      <th class="sort" width="60px" onclick="set_order('brand_id')">Brand</th>
      <th class="sort" width="60px" onclick="set_order('category_id')">Category</th>
      <th class="sort" width="60px" onclick="set_order('price')">Mkt Price</th>
      <th class="sort" width="60px" onclick="set_order('enabled_stock')">Stock</th>
      <th class="sort" width="60px" onclick="set_order('enabled_delivery')">Delivery</th>
      <th class="sort" width="40px" onclick="set_order('status')">Visible</th>
      <th class="sort" width="60px" onclick="set_order('date')">Date</th>
      <th class="sort" width="60px"></th>
    </tr>
    <?php foreach ($items->d as $idx => &$item) { ?>
    <tr class="<?php echo (($idx % 2 == 0) ? 'roweven' : 'rowodd'); ?>">
      <td title="<?php echo $item->name; ?>"><?php echo MiscUtils::getShortName($item->name, 40); ?></td>
      <td><?php echo get_brand($item->brand_id); ?></td>
      <td><?php echo get_category($item->category_id); ?></td>
      <td><?php echo $item->price; ?></td>
      <td <?php if ($item->alert__ == 1 && $item->enabled_stock == 1) echo 'style="color: #ff0000;"'; ?>><?php echo (($item->enabled_stock == 1) ? $item->_stock : 'Unlimited'); ?></td>
      <td><?php echo (($item->enabled_delivery == 1) ? 'Yes' : 'No'); ?></td>
      <td><input type="checkbox" <?php echo (($item->status == 1) ? 'checked="checked"' : ''); ?> onclick="update_available('<?php echo $item->id?>', this.checked)"></input></td>
      <td><?php echo $item->date; ?></td>
      <td>
        <img src="assets/imgs/edit.png" class="imgico" onclick="parent.location.href=parent.document.URL.replace('#', '') + '&script=index_product&id=<?php echo $item->track_id; ?>';"></img>
        <img src="assets/imgs/delete24.png" class="imgico" onclick="del_product('<?php echo $item->track_id; ?>');"></img>
      </td>
    </tr>
    <?php } ?>
    <?php if (count($items->d) == 0) { ?>
    <tr class="none" ><td colspan=9>None</td></tr>
    <?php } ?>
  </table>
  <div id="pagination"></div>
</div>
<script type="text/javascript" src="../../../libs/jquery/jquery-1.9.0.min.js"></script>
<script type="text/javascript" src="../../../incls/js/myutils.js"></script>
<script type="text/javascript" src="../../../incls/js/pagination.js"></script>

<script type="text/javascript">
  function set_order(col) {
    parent.location.href='http://<?php echo URL. "admin.php?i=$page_id&p=$items->p&q=" . (($items->q == 'ASC') ? 'DESC' : 'ASC'); ?>&o=' +  col + '&find=' + encodeURIComponent($('#s_kw')[0].value) + '&cat=' + $('#s_cat')[0].selectedIndex;
  }

  function del_product(track_id) {
    r = window.confirm('Are You Sure?');
    if (!r) {
      return;
    }
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=del_product&q=" + encodeURIComponent(track_id),
      success: function(msg){
        location.reload();
      }
    });
  }

  function update_available(id, available) {
    var obj = {
      id: id,
      status: available ? 1 : 0
    }
    $.ajax({
      type: "POST",
      url: "<?php echo basename(__FILE__, '.php'); ?>.server.php",
      data: "action=update_available&q=" + encodeURIComponent(JSON.stringify(obj)),
      success: function(msg){
        parent.location.reload();
      }
    });
  }
  
  function enter(ev) {
    if (window.event) {
      key = window.event.keyCode;
      isShift = window.event.shiftKey ? true : false;
    } else {
      key = ev.which;
    }
    if (key != 13) {
      return;
    }
    find();
  }
  
  function find() {
    var str = 'http://<?php echo URL . "admin.php?i=$page_id&find="; ?>' + encodeURIComponent($('#s_kw')[0].value) + '&cat=' + $('#s_cat')[0].selectedIndex;
    parent.location.href = str;
  }

  $(function(){
    var elm = document.getElementById('pagination');
    MyUtils.removeChildElements(elm);

    $('#s_cat')[0].selectedIndex = <?php echo $cat; ?>;
    
    new ModulePagination(document, elm, null, null, null, null, {
      page: <?php echo $items->p; ?>,
      total: <?php echo $items->t; ?>,
      limit: <?php echo $items->s; ?>,
      callbackFunc: function(page) { 
        parent.location.href = 'http://<?php echo URL . "admin.php?i=$page_id&o=$items->o&q=$items->q"; ?>&p=' + page + '&find=' + encodeURIComponent($('#s_kw')[0].value) + '&cat=' + $('#s_cat')[0].selectedIndex;
      },
      contenxt: this
    });
  });
</script>
</body>
</html>